import com.asiainfo.kbisheet.common.Util;
import com.asiainfo.kbisheet.components.AllExportForm;
import com.asiainfo.kbisheet.components.CreateAppRequestForm;
import com.asiainfo.kbisheet.components.SetForm;
import com.asiainfo.kbisheet.components.condition.ConditionGroup;
import com.asiainfo.kbisheet.control.*;
import com.asiainfo.kbisheet.event.AaaacashboxQueryAppOperJKStatusCompleteEvent;
import com.asiainfo.kbisheet.event.GetDataXMLCompleteEvent;
import com.asiainfo.kbisheet.model.KbsModel;
import com.asiainfo.kbisheet.model.MessageModel;
import com.asiainfo.kbisheet.model.SettingModel;
import com.asiainfo.kbisheet.util.yunnan.aaaacashbox.vo.QueryAppOperJKStatusQueryParam;
import com.asiainfo.kbisheet.util.yunnan.aaaacashbox.vo.QueryAppOperJKStatusQueryResult;
import com.asiainfo.kbisheet.vo.QueryVO;
import com.asiainfo.kbisheet.vo.SettingVO;
import com.asiainfo.kbisheet.vo.UserColumnSetVO;

import flash.events.Event;
import flash.net.URLRequest;

import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.core.IVisualElement;
import mx.managers.PopUpManager;

import spark.components.Button;
import spark.components.HGroup;
import spark.components.TitleWindow;
import spark.components.VGroup;
import spark.utils.TextFlowUtil;

[Bindable]
private var kbsModel:KbsModel = KbsModel.getInstance();

[Bindable]
private var settingModel:SettingModel = SettingModel.getInstance();

private var messageModel:MessageModel = MessageModel.getInstance();

/*需要在运行中根据配置文件实例化的控制器*/
private var kbsControl:IKbsControl;

/*为保证能动态加载类而定义的空变量*/
private var kbsControlClasses:* = [KbsControlSichuan,KbsControlYunnan];

private var settingControl:SettingControl = new SettingControl();

/*垂直按钮组容器*/
private var bvGroup:VGroup;

/*执行分页查询操作*/
public function doPaginate():void{
	kbsModel.queryVO.from = (kbsModel.currentPage - 1) * kbsModel.countPerPage + 1;
	kbsModel.queryVO.to = kbsModel.queryVO.from + kbsModel.countPerPage - 1;
	
	/*清空要显示的数据*/
	kbsAdg.dataXML = null;
	
	updateMessage("kbs.xml：doPaginate：执行查询:\r\n" + Util.getWheresString(kbsModel.queryVO.wheres));
	/*执行查询*/
	kbsControl.getDataXML();				
}

private function initApplication():void{
	/*获取服务器端的配置*/
	settingControl.addEventListener(Event.COMPLETE, getSettingHandler);				
	settingControl.getSettingVO();	
}

/* 获取到服务器端配置的处理 */
private function getSettingHandler(event:Event):void{
	var settingVO:SettingVO = settingModel.settingVO;
	
	/*根据kbsControlImpl创建类*/
	var kbsControlImplClass:Class = getDefinitionByName(settingVO.kbsControlImpl) as Class;
	settingModel.kbsControlImplClass = kbsControlImplClass;
	
	/*创建IKbsControl的实例*/
	kbsControl = settingModel.getKbsControl();
	
	/*messageModel消息监听*/
	messageModel.addEventListener(Event.CHANGE, updateMessageHandler);	
	
	updateMessage("kbs.xml：getSettingHandler：数字类型：" + settingVO.numbers);
	
	/*kbsControl监听*/
	kbsControl.addEventListener("getUserInfoComplete", getUserInfoCompleteHandler);
	kbsControl.addEventListener("loadDefineXmlComplete", loadDefineXmlCompleteHandler);
	kbsControl.addEventListener("getDataXMLComplete", getDataXMLCompleteHandler);
	kbsControl.addEventListener("aaaacashboxQueryAppOperJKStatusComplete", aaaacashboxQueryAppOperJKStatusCompleteHandler);
	
	/*测试状态下显示消息文本*/
	if(settingVO.debug){
		//taMessage.visible = true;
		vdbMain.addChild(taMessage);
	}
	
	/*获取用户信息*/
	var user_id:String = FlexGlobals.topLevelApplication.parameters["user_id"];
	updateMessage("kbs.xml：getSettingHandler：获取用户信息...");
	kbsControl.getUserInfo();				
}

private function aaaacashboxQueryAppOperJKStatusCompleteHandler(event:AaaacashboxQueryAppOperJKStatusCompleteEvent):void{
	var result:QueryAppOperJKStatusQueryResult  = event.value;
	var resultCode:String=result.resultCode;
	resultCode="success";
	if(resultCode=="success"){
		
		var next:String=result.next;
		next="apply";
		if(next=="pass_without_jk"||next=="pass_with_jk"||next=="error_autoswitch_yes"){
			doCreateExcel();
		}else if(next=="auth"){
			Alert.show("您已经创建了金库认证申请，请等待认证结束！","提示");
		}else if(next=="apply"){
			//			var helpWindow:TitleWindow = PopUpManager.createPopUp(this, CreateAppRequestForm, true) as TitleWindow;
			//			PopUpManager.centerPopUp(helpWindow);
			//			var carWindow:CreateAppRequestForm = PopUpManager.createPopUp(this, CreateAppRequestForm, true) as CreateAppRequestForm;
			var carWindow:CreateAppRequestForm = PopUpManager.createPopUp(this, CreateAppRequestForm, true) as CreateAppRequestForm;
			//以下值如何从获取private function doExport():void方法中
			carWindow.serviceUserName="longruyi";
			carWindow.servicePwd="lry123";
			carWindow.rootTicket="";
			carWindow.authMode=result.authModes;
			carWindow.appAccount="";
			carWindow.resNum="";
			carWindow.operationCode="";
			carWindow.functionCode="";
			carWindow.requestID=result.requestID;
			carWindow.userIP="10.168.0.111";
			PopUpManager.centerPopUp(carWindow);
		}
	}else if(resultCode=="error_no_applicant"){
		Alert.show("认证服务器没有该用户信息，请重新由IAM系统的Portal进行单点登录后，再进行此操作！","提示");
	}else if(resultCode=="error_authentication"){
		Alert.show("调用金库服务时输入的用户名或密码错误，认证失败，请重新输入正确的认证帐号以及密码！","提示");
	}else if(resultCode=="error_no_applicat_mobile"){
		Alert.show("您还没有设置手机号码，请通知IAM管理员设置手机号码，然后重新进行该操作!","提示");
	}else if(resultCode=="error_no_approver"){
		Alert.show("管理员未设置该场景审批人，或审批人信息丢失，请通知IAM管理员设置该场景审批人后，从新进行该操作!","提示");
	}else if(resultCode=="error_no_approver_mobile"){
		Alert.show("该场景审批人还未设置手机号码，请通知IAM管理员设置该场景审批人手机号码后，重新进行该操作!","提示");
	}else if(resultCode=="error_no_request"){
		Alert.show("没有该申请的信息，请联系IAM管理员确认该申请是否存在!","提示");
	}else if(resultCode=="validParam"){
		Alert.show("参数xxx为空，请检查您传递的参数没有遗漏，再重新进行该操作!","提示");
	}else{
		Alert.show("本次调用服务器失败！","提示");
	}
	
	kbsAdg.horizontalScrollPosition = kbsModel.horizontalScrollPosition;
}

private function getDataXMLCompleteHandler(event:GetDataXMLCompleteEvent):void{
	kbsAdg.dataXML = event.value;
	kbsAdg.horizontalScrollPosition = kbsModel.horizontalScrollPosition;
}

/* 获取用户信息完成 */
private function getUserInfoCompleteHandler(event:Event):void{
	/* 加载模板定义 */
	kbsControl.loadDefineXml();
}



/* 加载模板定义完成 */
private function loadDefineXmlCompleteHandler(event:Event):void{
	updateMessage("kbs.xml：loadDefineXmlCompleteHandler：呈现条件区...");
	updateMessage("kbsModel.enableExport = " + kbsModel.enableExport );
	/*导出*/
	if(kbsModel.enableExport){
		addButton(exportButton);
	}
	/*全部导出*/
	if(kbsModel.enableExportAll){
		addButton(exportAllButton);
	}
	/*自定义列*/
	addButton(setButton);
	
	/*外连接*/
	if(kbsModel.enableLink){
		addButton(linkButton);
	}
	
	conditionPanel.showConditions();
	
	/*查询按钮*/
	if(conditionPanel.numElements > 1){
		/*倒数第2个元素才是ConditionGroup，最后一个元素的VSpace*/
		var element : IVisualElement = conditionPanel.getElementAt(conditionPanel.numElements - 2);
		if(element is ConditionGroup){			
			ConditionGroup(element).addQueryButton(queryButton);
		}
	}
	
	
	/*备注*/
	if(kbsModel.showRemark){
		vdbMain.addChildAt(panelRemark, 1);
		panelRemark.height = kbsModel.remarkHeight;
		updateMessage("remarkTextFlowXML:" + kbsModel.remarkTextFlowXML);
		try{
			/*不多转一次的话会出现“意外命名空间”的异常*/
			rtRemark.textFlow = TextFlowUtil.importFromXML(new XML(kbsModel.remarkTextFlowXML.toXMLString()));
		}
		catch(error:Error){
			Alert.show(error.message);
		}
	}
}

/*在按钮组中添加按钮*/
private function addButton(button:Button):void{
	if(bvGroup == null || bvGroup.numElements > 1){
		bvGroup = new VGroup();
		groupButton.addElement(bvGroup);
	}
	
	bvGroup.addElement(button);
}

/* 更新消息 */
private function updateMessageHandler(event:Event=null):void{
	updateMessage(messageModel.message);
}

/* 更新消息 */
private function updateMessage(message:String):void{
	if(settingModel.settingVO.debug){
		taMessage.text = taMessage.text + "\r\n-----------------\r\n" + message;
	}
}

/*执行查询操作*/
private function doQuery():void{
	/*隐藏或显示列*/
	kbsAdg.hosColumns();
	/*执行查询*/
	var queryVO:QueryVO = new QueryVO();
	queryVO.sourceKey = kbsModel.kbsSheetVO.sourceKey;
	updateMessage("kbs.xml：doQuery()：sourceKey：" + queryVO.sourceKey);
	queryVO.dataBaseName = kbsModel.kbsSheetVO.databaseName;
	queryVO.tableName = getTableName();
	queryVO.sql = kbsModel.sql;
	queryVO.order = kbsModel.order;
	queryVO.wheres = kbsModel.getWheres();
	queryVO.columns = kbsModel.columns;
	kbsModel.queryVO = queryVO;
	kbsModel.currentPage = 1;
	doPaginate();
}

/*第一页*/
private function pageFirst():void{				
	kbsModel.currentPage = 1;
	doPaginate();
}
/*上一页*/
private function pagePreview():void{				
	kbsModel.currentPage = kbsModel.currentPage - 1;
	doPaginate();
}
/*下一页*/
private function pageNext():void{				
	kbsModel.currentPage = kbsModel.currentPage + 1;
	doPaginate();
}
/*第末页*/
private function pageLast():void{				
	kbsModel.currentPage = kbsModel.maxPage;
	doPaginate();
}
/*直接指定页数*/
private function nsPageChange():void{
	kbsModel.currentPage = nsPage.value;
	doPaginate();
}

private function doCreateExcel():void{	
	kbsControl.createExcel(kbsAdg.getExportXMLString());
}

/*执行导出操作*/
private function doExport():void{				
	//	kbsControl.createExcel(kbsAdg.getExportXMLString());
	var param:QueryAppOperJKStatusQueryParam = new QueryAppOperJKStatusQueryParam();
	param.serviceUserName="longry";
	param.servicePwd="long123";
	param.rootTicket="J6y2TqlRIWerscewJsqti8jG7rhsuyn83waZ60vjWFE=";
	param.resNum="bass2";
	param.appAccount="longry";
	param.functionCode="010203";
	param.operationCode="3003";
	param.userIP="10.173.148.34";
	//	param.serviceUserName=FlexGlobals.topLevelApplication.parameters["serviceUserName"];
	//	param.servicePwd=FlexGlobals.topLevelApplication.parameters["servicePwd"];
	//	param.rootTicket=FlexGlobals.topLevelApplication.parameters["rootTicket"];
	//	param.resNum=FlexGlobals.topLevelApplication.parameters["resNum"];
	//	param.appAccount=FlexGlobals.topLevelApplication.parameters["appAccount"];
	//	param.functionCode=FlexGlobals.topLevelApplication.parameters["functionCode"];
	//	param.operationCode=FlexGlobals.topLevelApplication.parameters["operationCode"];
	//	param.userIP=FlexGlobals.topLevelApplication.parameters["operationCode"];
	kbsControl.aaaacashboxQueryAppOperJKStatus(param);
}

/*全部导出操作*/
private function doAllExport():void{				
	var helpWindow:TitleWindow = PopUpManager.createPopUp(this, AllExportForm, true) as TitleWindow;
	PopUpManager.centerPopUp(helpWindow);
}

/*获取表名*/
private function getTableName():String{
	var tableName:String = kbsModel.kbsSheetVO.tableName;
	for each(var parameterXML:XML in kbsModel.sheetXML.parameters.parameter){
		var key:String = parameterXML.@key;
		var valueXML:XML = XML(parameterXML.value);
		var column:String = valueXML.@column;
		/*这里只会取条件框的第一个值，所以不能使用带参数的from-to类型的条件*/
		var value:String = kbsModel.getConditionItemValueByColumn(column);
		if(value){
			if(valueXML.hasOwnProperty('@start') && valueXML.hasOwnProperty('@end')){
				var start:int = int(valueXML.@start);
				var end:int = int(valueXML.@end);
				value = value.substring(start,end);						
			}						
		}
		tableName = tableName.replace(key,value);
	}
	
	return tableName;
}

/* 自定义列 */
private function doSet():void{		
	refreshUserColumns();
	var window:TitleWindow = PopUpManager.createPopUp(this, SetForm, true) as TitleWindow;				
	PopUpManager.centerPopUp(window);
}			

/*显示或隐藏列*/
private function refreshUserColumns():void{
	var groupedColumns : Array = new Array();
	
	for each(var column:XML in kbsModel.columnsXML.column){
		var userColumnSetVO:UserColumnSetVO = getUserColumn4XML(column);
		if(userColumnSetVO){
			groupedColumns.push(userColumnSetVO);
		}
	}
	kbsModel.userSetColumns = groupedColumns;
}			

private function getUserColumn4XML(columnXML:XML):UserColumnSetVO{
	var visible:Boolean = !(columnXML.hasOwnProperty('@hidden') && columnXML.@hidden == "true");
	if(columnXML.hasOwnProperty("visible")){
		var visibleXML:XML = XML(columnXML.visible);
		visible = 
			(visibleXML.hasOwnProperty('@dependence') && kbsModel.getConditionItemValueById(visibleXML.@dependence) == columnXML.@name) 
			|| (visibleXML.children().length() > 0 && kbsModel.isIfsTrue(visibleXML.children()));
	}
	if(visible && columnXML.hasOwnProperty('@uuid')){
		var userColumnSetVO : UserColumnSetVO = new UserColumnSetVO();
		userColumnSetVO.uuid = columnXML.@uuid;
		userColumnSetVO.visible = !kbsModel.hiddenColumnUUIDs.contains(userColumnSetVO.uuid);
		userColumnSetVO.headerText = columnXML.@title;
		if(columnXML.hasOwnProperty("column")){
			userColumnSetVO.children = new Array();
			for each(var column:XML in columnXML.column){
				var child:UserColumnSetVO = getUserColumn4XML(column);
				if(child){
					userColumnSetVO.children.push(child);
				}
			}
		}
		return userColumnSetVO;
	}
	else{
		return null;
	}
}

/*打开连接*/
private function doLink():void{ 
	navigateToURL(new URLRequest(kbsModel.linkURL));
}